﻿using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using ConfOrder.Properties;
using ConfOrderDS;
using ConfOrderDS.AppDSTableAdapters;
using DevExpress.Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace ConfOrder
{
    public partial class NewOrders : XForm
    {
        GridMenu ordersMenu;
        string lastMenuCaption = "";
        string newMenuCaption = "";
        int focusedRow = 0;
        DataTable errors = null;
        int Type = 1; //1:New Orders , 2:Pre-Submitted Orders

        public NewOrders(int type = 1)
        {
            InitializeComponent();
            this.Type = type;
        }



        BindingSource bsFabrics, bsDagilim;
        List<string> FixedPreSubmitColumns = new List<string>();

        private void Orders_Load(object sender, EventArgs e)
        {
            TAM.COOrderTableAdapter = new COOrderTableAdapter();
            TAM.COBreakdownTableAdapter = new COBreakdownTableAdapter();

            GetDetails("COOrder;COBreakdown", "COGetOrders2", Type, AppSession.UserInfo.CustomerId, true);

            ds.COBreakdown.Columns.Add("Total", typeof(int), "IsNull(A01, 0) + IsNull(A02, 0) + IsNull(A03, 0) + IsNull(A04, 0) + IsNull(A05, 0) + IsNull(A06, 0) + IsNull(A07, 0) + IsNull(A08, 0) + IsNull(A09, 0) + IsNull(A10, 0) + IsNull(A11, 0) + IsNull(A12, 0) + IsNull(A13, 0) + IsNull(A14, 0) + IsNull(A15, 0) + IsNull(A16, 0) + IsNull(A17, 0) + IsNull(A18, 0) + IsNull(A19, 0) + IsNull(A20, 0) + IsNull(A21, 0) + IsNull(A22, 0) + IsNull(A23, 0) + IsNull(A24, 0) + IsNull(A25, 0) + IsNull(A26, 0) + IsNull(A27, 0) + IsNull(A28, 0)");

            ds.COOrder.Columns.Add("TotalBDCount", typeof(int), "Count(Child(FK_COBreakdown_COOrder_OrderId).COBreakdownId)");
            ds.COOrder.Columns.Add("Total", typeof(int), "SUM(Child(FK_COBreakdown_COOrder_OrderId).Total)");

            ds.COOrder.Columns.Add("Brand", typeof(string));
            ds.COOrder.TableNewRow += COOrder_TableNewRow;

            bsFabrics = new BindingSource(ds, "COOrder");
            bsDagilim = new BindingSource(bsFabrics, "FK_COBreakdown_COOrder_OrderId");

            InitGridView(gvOrders, bsFabrics);
            InitGridView(gvDagilim, bsDagilim);

            gvOrders.MakeColumnInvisible("State");

            if (Type == 2)
                this.Text = "Pre-Submitted Shirt Orders";


            gvOrders.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gvDagilim.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;

            gvDagilim.MakeColumnInvisible("COBreakdownId", "TotalComputed", "COOrderId");
            gvOrders.MakeColumnInvisible("CustomerId", "Part", "OrderedDate", "ETD", "UserSubmitted", "TotalBDCount");
            gvOrders.Columns["Season"].OptionsColumn.AllowEdit = false;
            gvOrders.Columns["Season"].VisibleIndex = 3;

            gvOrders.Columns["COStyleId"].ColumnEdit = RepositoryManager.riStyle;
            gvOrders.Columns["State"].ColumnEdit = RepositoryManager.riState;
            gvOrders.Columns["OrderRefId"].ColumnEdit = RepositoryManager.riOrderRef;

            gvOrders.SelectionChanged += gvOrders_SelectionChanged;
            GridManager gm = GridManager.GetManager(gvOrders);
            gvOrders.ShowingEditor += gvOrders_ShowingEditor;
            gm.Pasting += gm_Pasting;


            ordersMenu = gm.GridMenu;
            if (Type == 1)
            {
                ordersMenu.AddMenu("Delete Row", DeleteRow, Resources.miDelete);
                ordersMenu.AddMenu("Delete the breakdown for selected positions", DeleteBreakdown);
                //gvOrders.Columns["State"].ColumnEdit = RepositoryManager.riState;
            }

            RepositoryItemGridLookUpEdit ri = RepositoryManager.riDagilim;
            gvOrders.Columns["DagilimId"].ColumnEdit = ri;
            ri.Closed += ri_Closed;
            bsFabrics.CurrentChanged += bsFabrics_CurrentChanged;

            gvOrders.SetCaptions("TalepTipiId:Order Type", "DagilimId:Breakdown Type", "COStyleId:Style", "COOrderId:RowId", "OrderRefId:Order Ref.", "ProductId:MainFabric", "Product1Id:Trim1", "Product2Id:Trim2", "Product3Id:Trim3", "Product4Id:Trim4", "Product5Id:Trim5", "Product6Id:Trim6");
            gvDagilim.SetCaptions("CountryId:Country");

            DagilimId = bsFabrics.GetCurrentValue("DagilimId").ToIntNN();
            DagilimChanged();

            gvOrders.BestFitColumns();
            gvDagilim.BestFitColumns();

            gvOrders.AddSummary("Total");
            gvDagilim.AddSummary("Total", "A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10",
                            "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20",
                            "A21", "A22", "A23", "A24", "A25", "A26", "A27", "A28");

            scc.SizeChanged += new EventHandler(MySizeChanged);
            gvOrders.CellValueChanged += gvOrders_CellValueChanged;

            gvOrders.SetViewCaption("Orders");
            gvDagilim.SetViewCaption("Breakdown");

            gvOrders.BringSideToBase("COOrderId", "Total");


            gvOrders.BringSideToBase("Total", "OrderRefId", "COStyleId", "Brand");

            gvOrders.Columns["Brand"].OptionsColumn.AllowEdit = false;

            gvDagilim.BringSideToBase("A01", "Total");

            gvOrders.RowCellStyle += gvOrders_RowCellStyle;
            gvDagilim.RowCellStyle += gvDagilim_RowCellStyle;
            gvDagilim.InvalidValueException += gvDagilim_InvalidValueException;

            //gvOrders.CustomColumnDisplayText += gvOrders_CustomColumnDisplayText;

            //    gleOrderRef =  RepositoryManager.GetGLESablon(RepositoryManager.dsi.COOrderRef, "OrderRef", "OrderRefId");

            RepositoryItemComboBox riPrepacking = new RepositoryItemComboBox();
            riPrepacking.Items.AddRange(new object[] { "YES", "NO" });
            riPrepacking.TextEditStyle = TextEditStyles.DisableTextEditor;
            gvDagilim.Columns["Prepacking"].ColumnEdit = riPrepacking;

            GridManager.GetManager(gvDagilim).Pasting += gvDagilim_Pasting;
            gvDagilim.ShowingEditor += gvDagilim_ShowingEditor;

            RepositoryItemComboBox riPackingInstruction = new RepositoryItemComboBox();
            riPackingInstruction.Items.AddRange(new object[] { "Per lot", "Per shop", "Per position", "Per size, per colour" });
            riPackingInstruction.TextEditStyle = TextEditStyles.DisableTextEditor;
            gvOrders.Columns["PackingInstruction"].ColumnEdit = riPackingInstruction;

            bbiOrderRef.EditValue = 0;

            repositoryItemGridLookUpEdit1.EditValueChanged += gleOrderRef_EditValueChanged;
            //repositoryItemGridLookUpEdit1.Closed += repositoryItemGridLookUpEdit1_Closed;

            repositoryItemGridLookUpEdit1_Closed(null, null);
            //foreach (DataRow dr in RepositoryManager.dsi.COOrderRef.Rows)
            //repositoryItemComboBox1.Items.Add("2009/01")


            FixedPreSubmitColumns.Add("Tape1");
            FixedPreSubmitColumns.Add("Tape2");
            FixedPreSubmitColumns.Add("Tape3");
            FixedPreSubmitColumns.Add("Tape4");
            FixedPreSubmitColumns.Add("Buttons");
            FixedPreSubmitColumns.Add("ButtonHole");
            FixedPreSubmitColumns.Add("ButtonAttach");
            FixedPreSubmitColumns.Add("ButtonAttachSleeveguard");
            FixedPreSubmitColumns.Add("ButtonholeAttachOnSleeveguard");
            FixedPreSubmitColumns.Add("ContrastStitching");
            FixedPreSubmitColumns.Add("ContrastButton");
            FixedPreSubmitColumns.Add("ContrastButtonHole");
            FixedPreSubmitColumns.Add("ContrastButtonAttach");
            FixedPreSubmitColumns.Add("FancyButton");
            FixedPreSubmitColumns.Add("FancyButtonHole");
            FixedPreSubmitColumns.Add("FancyButtonAttach");
            FixedPreSubmitColumns.Add("ColourTrench");


            MainToolbar.Visible = true;
        }

        void gvDagilim_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = CancelEdit(gvOrders.FocusedRowHandle, "");
        }

        void gvDagilim_Pasting(int rowHandle, DevExpress.XtraGrid.Columns.GridColumn column, object val, System.ComponentModel.CancelEventArgs ce)
        {
            ce.Cancel = CancelEdit(gvOrders.FocusedRowHandle, "");
        }

        void gm_Pasting(int rowHandle, DevExpress.XtraGrid.Columns.GridColumn column, object val, System.ComponentModel.CancelEventArgs ce)
        {
            ce.Cancel = CancelEdit(rowHandle, column.FieldName);
        }

        void gvOrders_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = CancelEdit(gvOrders.FocusedRowHandle, gvOrders.FocusedColumn.FieldName);
        }

        public bool CancelEdit(int RH, string colName)
        {
            bool cancel = false;
            if (gvOrders.GetRowCellValue(RH, "State").ToStringNN() == "F")
            {
                //if (colName.StartsWith("Product") || colName.StartsWith("Code") || colName == "RIDD" || colName == "ETA" || colName == "RemarkFabric" || colName.StartsWith("SpecialNotes"))
                if (FixedPreSubmitColumns.Contains(colName))
                    cancel = true;
                else
                    cancel = false;
            }
            if (cancel)
                XtraMessageBox.Show("You can change only columns which are not related with accessories in pre-submitted rows !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (!cancel)
                cancel = colName == "State";

            return cancel;
        }


        private void DeleteRow(object sender, EventArgs e)
        {
            ordersMenu.GridManager.gridUtility.DeleteRow();
        }

        private void DeleteBreakdown(object sender, EventArgs e)
        {
            gvOrders.EndEdit();

            foreach (int rowHandle in gvOrders.GetSelectedRows())
                //if (rowHandle > -1)
                foreach (DataRow dr in ds.COBreakdown.Select("COOrderId=" + gvOrders.GetDataRow(rowHandle)["COOrderId"]))
                    dr.Delete();
        }

        void gvDagilim_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
        {
            GridView view = sender as GridView;
            e.ExceptionMode = ExceptionMode.NoAction;
            int val = e.Value.ToIntNN();
            object defaultVal = view.GetRowCellValue(view.FocusedRowHandle, view.FocusedColumn);

            if (e.Value.ToStringNN() == "")
            {
                view.SetRowCellValue(gvDagilim.FocusedRowHandle, view.FocusedColumn, DBNull.Value);
            }
            else if (val < 0)
            {
                view.SetRowCellValue(gvDagilim.FocusedRowHandle, view.FocusedColumn, defaultVal);
            }
            else
            {
                e.ExceptionMode = ExceptionMode.DisplayError;
            }
        }

        void repositoryItemGridLookUpEdit1_Closed(object sender, EventArgs e)
        {
            DataTable dt;
            if (RepositoryManager.dsi.COOrderRef.Rows.Count > 0)
                dt = RepositoryManager.dsi.COOrderRef.CopyToDataTable();
            else
                dt = RepositoryManager.dsi.COOrderRef.Clone();

            dt.Columns.Remove("CustomerId");
            DataRow dr = dt.NewRow();
            dr["OrderRefId"] = 0;
            dr["OrderRef"] = "Show All";
            dr["BrandId"] = 0;
            dr["SezonId"] = 0;
            dt.Rows.InsertAt(dr, 0);

            repositoryItemGridLookUpEdit1.DataSource = dt;
            repositoryItemGridLookUpEdit1.DisplayMember = "OrderRef";
            repositoryItemGridLookUpEdit1.ValueMember = "OrderRefId";
            repositoryItemGridLookUpEdit1.View.OptionsView.ColumnAutoWidth = false;
            repositoryItemGridLookUpEdit1.PopulateViewColumns();
            repositoryItemGridLookUpEdit1.View.Columns["OrderRefId"].Caption = "#";
            repositoryItemGridLookUpEdit1.View.Columns["BrandId"].ColumnEdit = RI(Rp.Brand);
            repositoryItemGridLookUpEdit1.View.Columns["SezonId"].ColumnEdit = RI(Rp.Sezon);
            repositoryItemGridLookUpEdit1.TextEditStyle = TextEditStyles.DisableTextEditor;
            repositoryItemGridLookUpEdit1.PopupFilterMode = PopupFilterMode.Contains;
            repositoryItemGridLookUpEdit1.BestFitMode = BestFitMode.BestFitResizePopup;

            //repositoryItemGridLookUpEdit1.Enter += repositoryItemGridLookUpEdit1_Enter;
        }


        void gleOrderRef_EditValueChanged(object sender, EventArgs e)
        {
            SearchLookUpEdit gle = (SearchLookUpEdit)sender;
            int orderRefId = gle.EditValue.ToIntZero();

            if (orderRefId == 0)
                gvOrders.ActiveFilterString = "";
            else
                gvOrders.ActiveFilterString = "OrderRefId = '" + RepositoryManager.dsi.COOrderRef.FindByOrderRefId(orderRefId).OrderRef + "'";
        }


        void gvDagilim_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "Total")
                {
                    e.Appearance.BackColor = AppSession.ColorToplam;
                }
            }
        }


        void gvOrders_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                string fieldName = e.Column.FieldName;

                if (!gvOrders.IsCellSelected(e.RowHandle, e.Column))
                {
                    if (fieldName == "Total")
                    {
                        e.Appearance.BackColor = AppSession.ColorToplam;
                    }
                    else if ("OrderRefId".Contains(fieldName) && (e.CellValue == DBNull.Value || (int)e.CellValue == 0))
                    {
                        e.Appearance.BackColor = AppSession.ColorZorunlu;
                    }

                    else if ("COStyleId Pos DagilimId OrderRefId CodeMainFabric".Contains(fieldName) && e.CellValue == DBNull.Value)
                    {
                        e.Appearance.BackColor = AppSession.ColorZorunlu;
                    }

                    if ("Brand".Contains(fieldName) && gvOrders.GetRowCellValue(e.RowHandle, "COStyleId") == DBNull.Value)
                    {
                        e.Appearance.BackColor = AppSession.ColorZorunlu;
                    }

                    if (errors != null)
                    {
                        int orderId = gvOrders.GetDataRow(e.RowHandle)["COOrderId"].ToIntNN();
                        DataRow[] t1 = errors.Select("COOrderId=" + orderId + " and Note ='" + fieldName + "'");
                        if (t1.Length > 0)
                            e.Appearance.BackColor = System.Drawing.Color.Red;
                    }
                }
            }
        }

        //todo
        void gvOrders_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (gvOrders.SelectedRowsCount == 0)
                newMenuCaption = "";
            else if (gvOrders.SelectedRowsCount == 1)
                newMenuCaption = "Submit this order";
            else
                newMenuCaption = "Submit " + gvOrders.SelectedRowsCount + " selected orders";

            ordersMenu.RemoveMenu(lastMenuCaption.Replace("Submit", "Pre-Submit"));
            ordersMenu.RemoveMenu(lastMenuCaption);
            if (newMenuCaption != "")
            {
                ordersMenu.AddMenu(newMenuCaption, SubmitOrder, Resources.ok16x16);
                if (Type == 1)
                    ordersMenu.AddMenu(newMenuCaption.Replace("Submit", "Pre-Submit"), FinalizeOrder, null);
                lastMenuCaption = newMenuCaption;
            }
        }

        void SubmitOrder(object sender, EventArgs e)
        {
            SubmitOrder(2);
        }

        void FinalizeOrder(object sender, EventArgs e)
        {
            SubmitOrder(1);
        }

        private void SubmitOrder(int step)
        {
            focusedRow = gvOrders.FocusedRowHandle;
            bbiSave.PerformClick();


            System.Collections.Generic.List<int> iOrderIds = new System.Collections.Generic.List<int>();


            foreach (int rowHandle in gvOrders.GetSelectedRows())
            {
                if (rowHandle > -1)
                {
                    DataRow row = gvOrders.GetDataRow(rowHandle);

                    int dagilimId = row["DagilimId"].ToIntNN();
                    int coOrderId = row["COOrderId"].ToIntNN();
                    string str = row["ProductId"].ToString();
                    string str2 = row["CodeMainFabric"].ToString();

                    if (row["COStyleId"] == DBNull.Value)
                    {
                        XtraMessageBox.Show("Style can not be empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (row["Pos"] == DBNull.Value)
                    {
                        XtraMessageBox.Show("Pos can not be empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (dagilimId < 1)
                    {
                        XtraMessageBox.Show("Breakdown Type can not be empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (row["OrderRefId"].ToIntZero() == 0)
                    {
                        XtraMessageBox.Show("Order Reference can not be empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (step == 2 && row["CodeMainFabric"] == DBNull.Value)
                    {
                        XtraMessageBox.Show("Code Main Fabric can not be empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (row["Total"].ToIntNN() < 1)
                    {
                        XtraMessageBox.Show("Order Breakdown can not be empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (row["TalepTipiId"].ToIntNN() < 1)
                    {
                        XtraMessageBox.Show("Order Type can not be empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    //PackingInstruction alanlarını set ediyoruz
                    if (row["PackingInstruction"] == DBNull.Value)
                    {
                        if (row["TotalBDCount"].ToIntNN() == 1)
                            gvOrders.SetRowCellValue(rowHandle, "PackingInstruction", "Per size per colour");
                        else if (row["TotalBDCount"].ToIntNN() > 1)
                            gvOrders.SetRowCellValue(rowHandle, "PackingInstruction", "Per shop");
                    }

                    iOrderIds.Add(coOrderId);
                }
            }

            string OrderIds = string.Join(",", iOrderIds);
            errors = AppSession.DataManager.ExecuteDataTable("COCheckOrder", OrderIds);

            if ((step == 1 && errors.Select("Code not in (1,2)").Length > 0) || (step == 2 && errors.Rows.Count > 0))
            {
                string info = "There are error(s) in " + errors.Rows.Count + " columns. You can see the error messages by hovering over the columns in red.";
                foreach (DataRow dr in errors.Rows)
                    info += "\r\n\tRowId:" + dr["COOrderId"] + "\tStyle:" + dr["Style"] + "\tColumn:" + dr["Note"] + "\t\tError:" + dr["Expl"].ToStringNN();

                XtraMessageBox.Show(info);
            }


            else
            {
                string message = "";
                char state = '-';
                string SPName = "";
                if (step == 1)
                {
                    message = "Pre-Submitted orders will be put on process therefore changes (except fabric changes) on pre-submitted orders can not be made after confirmation.";
                    state = 'F';
                }
                else if (step == 2)
                {
                    message = "Submitted orders will be put on process therefore changes on submitted orders can not be made after confirmation.";
                    state = 'O';
                }

                DialogResult dr = XtraMessageBox.Show(message + "\r\n\r\nAre you sure?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    //foreach (int rowHandle in gvOrders.GetSelectedRows())
                    //    if (rowHandle > -1)
                    //        gvOrders.SetRowCellValue(rowHandle, "State", state);

                    //bbiSave.PerformClick();

                    switch (AppSession.UserInfo.CustomerId)
                    {
                        case 75:
                            ExecQuery("COSubmitOrder2", OrderIds, AppSession.UserInfo.UserId, step);
                            break;
                        case 262:
                            ExecQuery("COSubmitOrderLedbury2", OrderIds, AppSession.UserInfo.UserId, step);
                            break;
                        default:
                            break;
                    }

                    ds.COOrder.Clear();
                    ds.COStyle.Clear();
                    GetDetails("COOrder;COBreakdown", "COGetOrders2", Type, AppSession.UserInfo.CustomerId, true);
                    if (focusedRow + 1 >= gvOrders.RowCount)
                    {
                        gvOrders.FocusedRowHandle = gvOrders.RowCount - 2;
                    }
                    else
                    {
                        gvOrders.FocusedRowHandle = focusedRow;
                    }

                    if (Environment.MachineName != "KGULCAN")
                        ExecQuery("COInform", AppSession.UserInfo.CustomerId, step + 2);
                }
            }
        }
        void COOrder_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["CustomerId"] = AppSession.UserInfo.CustomerId;

            int selectedOrderRefId = bbiOrderRef.EditValue.ToIntNN();

            if (selectedOrderRefId > -1)
                e.Row["OrderRefId"] = selectedOrderRefId;
        }

        void gvOrders_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            gvOrders.CellValueChanged -= gvOrders_CellValueChanged;

            if (e.Column.FieldName == "CodeMainFabric")
            {
                string KumasKodu = e.Value.ToStringNN().Trim();
                DataRow[] kumas = RepositoryManager.dsi.V_Kumas.Select("Name='" + KumasKodu + "'");
                int KumasId = kumas.Length == 0 || KumasKodu == "" ? 0 : kumas[0]["ProductId"].ToIntZero();
                int ProductId = gvOrders.GetRowCellValue(e.RowHandle, "ProductId").ToIntZero();
                if (ProductId != KumasId)
                {
                    if (KumasId != 0)
                        gvOrders.SetRowCellValue(e.RowHandle, "ProductId", KumasId);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "ProductId", DBNull.Value);
                }

                //Care Label is set here each time the ProductId is changed: (Alttaki ile birlikte düşünüp kod yeniden düzenlenebilir)
                int KompozisyonId = kumas.Length == 0 ? 0 : kumas[0]["KompozisyonId"].ToIntZero();
                DataTable dt = AppSession.DataManager.ExecuteDataTableByQuery("select Name from Kompozisyon where KompozisyonId = " + KompozisyonId.ToString());
                string kompozisyon = DBNull.Value.ToString();
                if (dt.Rows.Count > 0)
                    kompozisyon = dt.Rows[0].Field<string>("Name").ToStringNN();

                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "ProductId").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeMainFabric").ToStringNN();
                if (ProductName != "")
                {
                    gvOrders.SetRowCellValue(e.RowHandle, "CodeMainFabric", ProductName);
                    gvOrders.SetRowCellValue(e.RowHandle, "CareLabel", kompozisyon);
                }
                //else
                //    gvOrders.SetRowCellValue(e.RowHandle, "CodeMainFabric", DBNull.Value);
            }
            else if (e.Column.FieldName == "ProductId")
            {
                //Care Label is set here each time the ProductId is changed:
                DataRow[] kumas2 = RepositoryManager.dsi.V_Kumas.Select("ProductId=" + e.Value.ToIntNN());
                int KompozisyonId = kumas2.Length == 0 ? 0 : kumas2[0]["KompozisyonId"].ToIntZero();
                DataTable dt = AppSession.DataManager.ExecuteDataTableByQuery("select Name from Kompozisyon where KompozisyonId = " + KompozisyonId.ToString());
                string kompozisyon = DBNull.Value.ToString();
                if (dt.Rows.Count > 0)
                    kompozisyon = dt.Rows[0].Field<string>("Name").ToStringNN();

                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "ProductId").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeMainFabric").ToStringNN();
                if (codemainfabric != ProductName)
                {
                    if (ProductName != "")
                    {
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeMainFabric", ProductName);
                        gvOrders.SetRowCellValue(e.RowHandle, "CareLabel", kompozisyon);
                    }
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeMainFabric", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "CodeTrim1")
            {
                string KumasKodu = e.Value.ToStringNN().Trim();
                DataRow[] kumas = RepositoryManager.dsi.V_Kumas.Select("Name='" + KumasKodu + "'");
                int KumasId = kumas.Length == 0 || KumasKodu == "" ? 0 : kumas[0]["ProductId"].ToIntZero();
                int ProductId = gvOrders.GetRowCellValue(e.RowHandle, "Product1Id").ToIntZero();
                if (ProductId != KumasId)
                {
                    if (KumasId != 0)
                        gvOrders.SetRowCellValue(e.RowHandle, "Product1Id", KumasId);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "Product1Id", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "Product1Id")
            {
                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "Product1Id").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeTrim1").ToStringNN();
                if (codemainfabric != ProductName)
                {
                    if (ProductName != "")
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim1", ProductName);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim1", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "CodeTrim2")
            {
                string KumasKodu = e.Value.ToStringNN().Trim();
                DataRow[] kumas = RepositoryManager.dsi.V_Kumas.Select("Name='" + KumasKodu + "'");
                int KumasId = kumas.Length == 0 || KumasKodu == "" ? 0 : kumas[0]["ProductId"].ToIntZero();
                int ProductId = gvOrders.GetRowCellValue(e.RowHandle, "Product2Id").ToIntZero();
                if (ProductId != KumasId)
                {
                    if (KumasId != 0)
                        gvOrders.SetRowCellValue(e.RowHandle, "Product2Id", KumasId);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "Product2Id", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "Product2Id")
            {
                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "Product2Id").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeTrim2").ToStringNN();
                if (codemainfabric != ProductName)
                {
                    if (ProductName != "")
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim2", ProductName);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim2", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "CodeTrim3")
            {
                string KumasKodu = e.Value.ToStringNN().Trim();
                DataRow[] kumas = RepositoryManager.dsi.V_Kumas.Select("Name='" + KumasKodu + "'");
                int KumasId = kumas.Length == 0 || KumasKodu == "" ? 0 : kumas[0]["ProductId"].ToIntZero();
                int ProductId = gvOrders.GetRowCellValue(e.RowHandle, "Product3Id").ToIntZero();
                if (ProductId != KumasId)
                {
                    if (KumasId != 0)
                        gvOrders.SetRowCellValue(e.RowHandle, "Product3Id", KumasId);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "Product3Id", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "Product3Id")
            {
                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "Product3Id").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeTrim3").ToStringNN();
                if (codemainfabric != ProductName)
                {
                    if (ProductName != "")
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim3", ProductName);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim3", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "CodeTrim4")
            {
                string KumasKodu = e.Value.ToStringNN().Trim();
                DataRow[] kumas = RepositoryManager.dsi.V_Kumas.Select("Name='" + KumasKodu + "'");
                int KumasId = kumas.Length == 0 || KumasKodu == "" ? 0 : kumas[0]["ProductId"].ToIntZero();
                int ProductId = gvOrders.GetRowCellValue(e.RowHandle, "Product4Id").ToIntZero();
                if (ProductId != KumasId)
                {
                    if (KumasId != 0)
                        gvOrders.SetRowCellValue(e.RowHandle, "Product4Id", KumasId);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "Product4Id", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "Product4Id")
            {
                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "Product4Id").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeTrim4").ToStringNN();
                if (codemainfabric != ProductName)
                {
                    if (ProductName != "")
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim4", ProductName);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim4", DBNull.Value);
                }
            }

            else if (e.Column.FieldName == "CodeTrim5")
            {
                string KumasKodu = e.Value.ToStringNN().Trim();
                DataRow[] kumas = RepositoryManager.dsi.V_Kumas.Select("Name='" + KumasKodu + "'");
                int KumasId = kumas.Length == 0 || KumasKodu == "" ? 0 : kumas[0]["ProductId"].ToIntZero();
                int ProductId = gvOrders.GetRowCellValue(e.RowHandle, "Product5Id").ToIntZero();
                if (ProductId != KumasId)
                {
                    if (KumasId != 0)
                        gvOrders.SetRowCellValue(e.RowHandle, "Product5Id", KumasId);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "Product5Id", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "Product5Id")
            {
                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "Product5Id").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeTrim5").ToStringNN();
                if (codemainfabric != ProductName)
                {
                    if (ProductName != "")
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim5", ProductName);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim5", DBNull.Value);
                }
            }


            else if (e.Column.FieldName == "CodeTrim6")
            {
                string KumasKodu = e.Value.ToStringNN().Trim();
                DataRow[] kumas = RepositoryManager.dsi.V_Kumas.Select("Name='" + KumasKodu + "'");
                int KumasId = kumas.Length == 0 || KumasKodu == "" ? 0 : kumas[0]["ProductId"].ToIntZero();
                int ProductId = gvOrders.GetRowCellValue(e.RowHandle, "Product6Id").ToIntZero();
                if (ProductId != KumasId)
                {
                    if (KumasId != 0)
                        gvOrders.SetRowCellValue(e.RowHandle, "Product6Id", KumasId);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "Product6Id", DBNull.Value);
                }
            }
            else if (e.Column.FieldName == "Product6Id")
            {
                string ProductName = gvOrders.GetRowCellDisplayText(e.RowHandle, "Product6Id").ToStringNN();
                string codemainfabric = gvOrders.GetRowCellValue(e.RowHandle, "CodeTrim6").ToStringNN();
                if (codemainfabric != ProductName)
                {
                    if (ProductName != "")
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim6", ProductName);
                    else
                        gvOrders.SetRowCellValue(e.RowHandle, "CodeTrim6", DBNull.Value);
                }
            }


            gvOrders.BestFitColumns();
            gvOrders.CellValueChanged += gvOrders_CellValueChanged;
        }

        int DagilimId = 0;
        void bsFabrics_CurrentChanged(object sender, EventArgs e)
        {
            DagilimId = bsFabrics.GetCurrentValue("DagilimId").ToIntNN();
            DagilimChanged();
        }

        void ri_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            DagilimId = (sender as BaseEdit).EditValue.ToIntNN();
            DagilimChanged();
        }

        private void DagilimChanged()
        {
            try
            {
                gvDagilim.CloseEditor();
                gvDagilim.BeginUpdate();

                AppDS.DagilimRow r = RepositoryManager.dsi.Dagilim.FindByDagilimId(DagilimId);
                if (r != null)
                    for (int i = 1; i <= 28; i++)
                    {
                        string fieldName = String.Format("A{0:00}", i);
                        string cap = r[String.Format("A{0:00}", i)].ToString();

                        gvDagilim.Columns[fieldName].VisibleIndex = 100 + i;

                        if (cap != "")
                            gvDagilim.Columns[fieldName].Caption = cap;
                        else
                            gvDagilim.Columns[fieldName].Visible = false;
                        //gvDagilim.Columns[fieldName].Caption = cap != string.Empty ? cap : " ";
                    }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                gvDagilim.EndUpdate();
                gvDagilim.BestFitColumns();
            }
        }

        private void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvOrders.CloseEditor();
            bsFabrics.EndEdit();

            //string order = ds.COOrder.SerializeChanges();
            //if (order != "")
            //    AppSession.DataManager.ExecuteNonQuery("COInsLog", "Order", order);


            //string breakdown = ds.COBreakdown.SerializeChanges();
            //if (breakdown != "")
            //    AppSession.DataManager.ExecuteNonQuery("COInsLog", "BreakDown", breakdown);

            Save();

            Notify("Saved successfully.");
        }

        private void bbiRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            focusedRow = gvOrders.FocusedRowHandle;

            gvOrders.CloseEditor();
            bsFabrics.EndEdit();

            if (ds.HasChanges())
            {
                bbiSave.PerformClick();
            }

            ds.COOrder.Clear();
            ds.COStyle.Clear();
            GetDetails("COOrder;COBreakdown", "COGetOrders2", Type, AppSession.UserInfo.CustomerId, true);

            if (focusedRow + 1 >= gvOrders.RowCount)
            {
                gvOrders.FocusedRowHandle = gvOrders.RowCount - 2;
            }
            else
            {
                gvOrders.FocusedRowHandle = focusedRow;
            }
        }

        private void toolTipController1_GetActiveObjectInfo(object sender, DevExpress.Utils.ToolTipControllerGetActiveObjectInfoEventArgs e)
        {
            if (e.Info == null && e.SelectedControl == gcFabrics)
            {
                GridView view = gcFabrics.FocusedView as GridView;
                GridHitInfo info = view.CalcHitInfo(e.ControlMousePosition);

                if (info.InRowCell && info.RowHandle > -1 && errors != null)
                {
                    int orderId = gvOrders.GetDataRow(info.RowHandle)["COOrderId"].ToIntNN();
                    string text = "";

                    foreach (DataRow dr in this.errors.Select("COOrderId=" + orderId))
                        if (dr["Note"].ToString() == info.Column.FieldName)
                            text = dr["Expl"].ToString();

                    string cellKey = info.RowHandle.ToString() + " - " + info.Column.ToString();
                    e.Info = new DevExpress.Utils.ToolTipControlInfo(cellKey, text);
                }
            }
        }

        private void btnImport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult dr = XtraMessageBox.Show("All changes will be saved. Do you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == System.Windows.Forms.DialogResult.Yes)
                using (ConfOrder.ImportBreakdown imp = new ConfOrder.ImportBreakdown())
                {
                    DialogResult drImport = imp.ShowDialog();
                    if (drImport == System.Windows.Forms.DialogResult.OK)
                        btnRefresh.PerformClick();

                }
        }
    }
}